<template>
  <view class="container">
    <view class="address-box">
      <u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <u-form-item label="姓名" prop="fullName" labelWidth="90" borderBottom ref="item-name">
          <u-input type="text" maxlength="11" v-model="formData.fullName" clearable placeholder="请填写姓名"
            border="none"></u-input>
        </u-form-item>

        <u-form-item label="联系电话" prop="mobile" labelWidth="90" borderBottom ref="item-mobile">
          <u-input type="number" maxlength="11" v-model="formData.mobile" clearable placeholder="请填写联系电话"
            border="none"></u-input>
        </u-form-item>

        <u-form-item label="选择地区" prop="address" labelWidth="90" borderBottom @click="openChooseLocation()"
          ref="item-areaText">
          <u--input v-model="formData.address" disabled disabledColor="#ffffff" placeholder="请选择省市地区"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
          <!-- <w-picker :visible.sync="regionVisible" mode="region" :value="defaultRegion" default-type="value" :hide-area="false" @confirm="onConfirm($event, 'region')" @cancel="onCancel" ref="region"></w-picker> -->
        </u-form-item>

        <u-form-item label="详细地址" prop="detailedAddress" labelWidth="90" borderBottom ref="item-detail">
          <u--input placeholder="例: 1号楼1单元101室" v-model="formData.detailedAddress" border="none"></u--input>
        </u-form-item>

        <u-form-item label="默认地址" prop="defaulted" labelWidth="90" borderBottom ref="item-type">
          <u-radio-group v-model="formData.defaulted">
            <u-radio :customStyle="{ marginRight: '16px' }" v-for="(item, index) in typeList" :key="index"
              :label="item.name" :name="item.value"></u-radio>
          </u-radio-group>
        </u-form-item>

        <view class="btn-group">
          <u-button type="primary" text="保存地址" customStyle="margin-top: 50px" @click="handleSubmit" color="linear-gradient(to right, #119FAF, #41C69E)"></u-button>
        </view>
      </u--form>
    </view>
  </view>
</template>

<script>
  import {
    getAddressById,
    updateAddress
  } from '../../api/address'

  export default {
    data() {
      return {
        id: '',
        regionVisible: false,
        defaultRegion: ['110000', '110100', '110101'],
        typeList: [{
            name: '是',
            value: true
          },
          {
            name: '否',
            value: false
          }
        ],
        formData: {
          id: undefined,
          fullName: '',
          mobile: '',
          address: '',
          longitude: '',
          latitude: '',
          detailedAddress: '',
          defaulted: false
        },
        rules: {
          fullName: [{
              type: 'string',
              min: 2,
              max: 12,
              required: true,
              message: '请填写名称',
              trigger: ['blur', 'change']
            },
            {
              message: '名称不能为空',
              // 触发器可以同时用blur和change
              trigger: ['change', 'blur']
            }
          ],
          mobile: [{
              type: 'integer',
              required: true,
              message: '请填写手机号',
              trigger: ['blur', 'change']
            },
            {
              // 自定义验证函数，见上说明
              validator: (rule, value, callback) => {
                // 上面有说，返回true表示校验通过，返回false表示不通过
                // uni.$u.test.mobile()就是返回true或者false的
                return uni.$u.test.mobile(value)
              },
              message: '手机号码不正确',
              // 触发器可以同时用blur和change
              trigger: ['change', 'blur']
            }
          ],
          address: {
            type: 'string',
            required: true,
            message: '请选择省市地区',
            trigger: ['blur', 'change']
          },
          detailedAddress: {
            type: 'string',
            min: 6,
            max: 30,
            required: true,
            message: '请填写详细地址',
            trigger: ['blur', 'change']
          }
        }
      }
    },
    onLoad(e) {
      if (!e.addressId) {
        uni.$u.toast('请求参数错误')
      } else {
        this.id = e.addressId
        this.loadAddressData()
      }
    },
    methods: {
      getLocation() {
        const that = this
        wx.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          success: function(res) {
            that.point.longitude = res.longitude;
            that.point.latitude = res.latitude;
          },
          fail: function(res) {
            uni.navigateBack()
            uni.$u.toast(JSON.stringify(res))
          }
        })
      },
      openChooseLocation(opt) {
        let that = this

        uni.chooseLocation({
          latitude: opt?.latitude || that.point.latitude,
          longitude: opt?.longitude || that.point.longitude,
          success: function(res) {
            if (!res.name) {
              return uni.showToast({
                title: '请重新选择位置',
                icon: 'none'
              });
            }
            that.formData.address = res.address
            that.formData.latitude = res.latitude
            that.formData.longitude = res.longitude
            that.flag = 10
          },
          fail: function(info) { //失败回调
            console.log('调取失败')
            console.log(info)
          }
        })
      },
      loadAddressData() {
        getAddressById({
          id: this.id
        }).then(res => {
          this.formData = res.data
        })
      },
      onConfirm(res) {
        this.formData.areaText = res.result
        this.formData.areaCode = res.value[2]
      },
      onCancel() {},
      hideKeyboard() {
        uni.hideKeyboard()
      },
      handleSubmit() {
        this.$refs.form.validate().then(res => {
          this.formData.detailAddress = this.formData.areaText + this.formData.detail
          console.log(this.formData)
          updateAddress(this.formData).then(res => {
            uni.$u.toast('地址已更新')
            setTimeout(() => {
              uni.navigateBack()
            }, 300)
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .address-box {
    width: 690rpx;
    margin: 0 auto;
    padding-top: 30rpx;
  }
</style>
